/*
 *   Copyright 1999-2016 Asiainfo Technologies(China),Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.asiainfo.redis.service.busidatawriter;

import com.asiainfo.redis.entity.BusiDataRule;
import com.asiainfo.redis.repository.BusiTypeRepository;
import com.asiainfo.redis.utils.SpringContextUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.RedisClusterConnection;
import redis.clients.util.SafeEncoder;

import java.sql.ResultSet;
import java.util.Set;

/**
 * @version v 1.0 on 2016/7/27 16:01
 * @auther william.xu
 */
public abstract class BusiDataRedisWriter {

    protected static final Logger LOGGER = LoggerFactory.getLogger(BusiDataRedisWriter.class);

    protected BusiTypeRepository busiTypeRepository;

    protected String busiTypeCode;
    protected BusiDataRule busiDataRule;

    protected RedisClusterConnection connection;

    protected Integer operFlag;//0-更新写入redis；1-从redis中删除

    public BusiDataRedisWriter(Integer operFlag) {
        this.busiTypeRepository = SpringContextUtil.getBean(BusiTypeRepository.class);
        this.operFlag = operFlag;
    }

    public abstract void doWrite(ResultSet rst) throws Exception;

    protected String object2String(Object object) throws Exception{
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(object);
    }

    protected void publishMessage(byte[] key){
        //发布消息，channel=业务系统编码，message=operFlag:更新的key
        //客户端一旦订阅了该channel，将获取当前更新的key，从而从redis获取该key的值，更新到二级缓存中
        connection.publish(SafeEncoder.encode(busiTypeCode),
                SafeEncoder.encode((operFlag + ":" + SafeEncoder.encode(key))));
    }

    public BusiDataRule getBusiDataRule() {
        return busiDataRule;
    }

    public void setBusiDataRule(BusiDataRule busiDataRule) {
        this.busiDataRule = busiDataRule;
        this.busiTypeCode = busiTypeRepository.findOne(busiDataRule.getBusiTypeId()).getBusiCode();
    }

    public RedisClusterConnection getConnection() {
        return connection;
    }

    public void setConnection(RedisClusterConnection connection) {
        this.connection = connection;
    }

    //删除【业务编码:KEY前缀:】的所有key
    public void removeAllRedisDataByBusiTypeCodeAndKeyPrefix() throws Exception {
        String keyQuery = this.busiTypeCode + ":" + busiDataRule.getKeyPrefix() + ":";

        Set<byte[]> keyList = connection.keys(SafeEncoder.encode(keyQuery + "*"));
        LOGGER.info("正在清除Key前缀="+keyQuery+", 总数="+ keyList.size());
        for (byte[] key : keyList) {
            connection.del(key);
        }
    }

}
